package spe.model.spem;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.ImageDescriptor;

import spe.model.spem.SPEMElement;
import spe.model.registry.SPEElementRegistry;
import spe.model.registry.SPERegistryRegistry;

public class SPEMFactoryImpl implements SPEMFactory
{	
	private SPEElementRegistry registry;
	private String editorId;
	
	public SPEMFactoryImpl(String editorId)
	{
		this.editorId = editorId;
		registry = SPERegistryRegistry.getSPEElementRegistry(editorId);
	}
	
	public static SPEMFactory createInstance(String editorId)
	{
		return new SPEMFactoryImpl(editorId);
	}
	
	private ImageDescriptor getImageDescriptor(IConfigurationElement element)
	{
		ImageDescriptor icon = null;
		String iconPath = element.getAttribute("icon");
		if (iconPath != null) {
			icon = ImageDescriptor.createFromURL(Platform.getBundle(element.getContributor().getName()).getEntry(iconPath));
		}
		return icon;
	}
	
	public SPEMElement createElementById(String extensionElementId)
	{
		try {
			IConfigurationElement element = registry.getConfigurationElementById(extensionElementId);
			if (element == null) return null;
			SPEMElement result = (SPEMElement)element.createExecutableExtension("modelClass");
			result.setElementId(element.getAttribute("id"));
			result.setNamePrefix(element.getAttribute("name"));
			String id = getId(element.getAttribute("NamePrefix"));
			result.setId(id);
			//System.out.println(String.format("[SPEMFactory] Element %s; id: %s", result, id));
			result.setIconDescriptor(getImageDescriptor(element));
			result.setFactory(this);
			result.initialize();
			return result;
		} catch (CoreException e) {
			throw new RuntimeException("Creation of executable extension failed", e);
		}
	}
	
	private String getId(String idprefix)
	{
		//SimpleDateFormat date_format = new SimpleDateFormat("yyyyMMdd");
		return String.format("%s%d", idprefix, System.currentTimeMillis());
	}

	@Override
	public String getEditorId()
	{
		return this.editorId;
	}

	@Override
	public void setEditorId(String id) {
		this.editorId = id;
		
	}
}
